// components/select/select.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 弹出弹层标识
    flag: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal) {
        this.setData({
          show: newVal,
        })
      },
    },
    // 列表选项数据
    list: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        let len = newVal.length
        this.setData({
          listFilter: [ ...(new Array(len)).values() ],
        })
      },
    },
    // 选项 id别称
    oid: {
      type: String,
      value: 'id',
    },
    // 选项 name别称
    name: {
      type: String,
      value: 'name',
    },
    // 是否需要搜索栏
    search: {
      type: Boolean,
      value: false,
    },
    // 是否需要新增
    add: {
      type: Boolean,
      value: false,
    },
    // placeholder
    plc: {
      type: String,
      value: '请输入',
    },
    // 默认选中值
    dfltVal: {
      type: String,
      optionalTypes: [Number, Boolean, ],
      value: '',
      observer(newVal, oldVal) {
        let { list, oid, } = this.data,
            selArr = list.filter(item => item[oid] == newVal)
        if(selArr.length) this.select({
          currentTarget: {
            dataset: {
              item: selArr[0],
            },
          },
        })
      },
    },
  },

  // 监听
  observers: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,

    searchVal: '',

    listFilter: [],
  },

  // 生命周期
  lifetimes: {
    created() {},
    attached() {},
    ready() {},
    moved() {},
    detached() {},
    error() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 双向绑定 报警告处理
    // inputIpt(e) {},
    inputIpt: wx.$util.debounce(function(e) {
      let { list, listFilter, name, } = this.data,
          val = e.detail.value
      list.forEach((item, i) => {
        let compVal = item[name]
        if(typeof compVal !== 'string') compVal += ''
        // listFilter[i] = !(item[name].indexOf(val) > -1)
        listFilter[i] = !(compVal.indexOf(val) > -1)
      })
      this.setData({
        listFilter,
      })
    }, 100),

    // 点击了键盘的搜索
    searchIpt(e) {},
    // 清空输入框
    emptyIpt(e) {
      let { listFilter, } = this.data
      listFilter.forEach((item, i) => listFilter[i] = false)
      this.setData({
        searchVal: '',
        listFilter,
      })
    },

    // 新增
    onAdd(e) {
      this.triggerEvent('add')
    },

    // 选中选项
    select(e) {
      this.triggerEvent('select', e.currentTarget.dataset.item)
      this.closePopup()
    },

    closePopup(e) {
      this.setData({
        show: false,
      })
      //240122 yan 注释，取消判断e，所有调用此函数都触发自定义事件，实现双向绑定
      // if(e) this.triggerEvent('close')
      this.triggerEvent('close')
    //  240122 end
    },
  }
})
